﻿using System;
using System.IO;

namespace ImageProcessing.Comm
{
    public class FileToMemoryStreamConverter
    {
        public static MemoryStream ConvertStreamToMemoryStream(Stream inputStream)
        {
            MemoryStream memoryStream = new MemoryStream();

            inputStream.CopyTo(memoryStream);

            memoryStream.Position = 0;

            return memoryStream;
        }

        public static MemoryStream ConvertFileToMemoryStream(string filePath)
        {
            // 确保文件存在
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("The file does not exist.", filePath);
            }

            // 创建一个FileStream来读取文件
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                // 确定文件大小
                long fileLength = fileStream.Length;
                if (fileLength > int.MaxValue)
                {
                    throw new IOException("The file is too large to be read into a MemoryStream.");
                }

                // 读取文件内容到一个字节数组
                byte[] fileBytes = new byte[fileLength];
                fileStream.Read(fileBytes, 0, (int)fileLength);

                // 创建MemoryStream并使用字节数组初始化
                return new MemoryStream(fileBytes);
            }
        }
    }
}